//To-do: remove debugging
#include <stdio.h>
/**
 * AppleIIGo
 * IWM (Integrated Woz Machine) class
 * (C) 2008 by Marc S. Ressl (mressl@umich.edu)
 * Released under the GPL
 */

#include "IWM.h"

IWM::IWM(Motherboard * motherboard, char * slotDeviceName) :
DiskIIController(motherboard, slotDeviceName) {
	isDiskIIController = false;
}

void IWM::onResetAsserted(bool isRestart) {
	DiskIIController::onResetAsserted(isRestart);
	
	modeRegister = 0;
}

UINT8 IWM::setRegister(UINT8 value) {
	switch (sequencerRegister) {
		case SEQUENCERREGISTER_READ | SEQUENCERREGISTER_SHIFT:
			isWriteUnderrun = false;
			if (!isDriveEnabled)
				break;
			if (isLatchMode) {
				UINT8 value = readDataRegister;
				readDataRegister = 0;
				return value;
			} else
				return shiftRegister;
		case SEQUENCERREGISTER_READ | SEQUENCERREGISTER_LOAD:
			isWriteUnderrun = false;
			return getStatusRegister();
		case SEQUENCERREGISTER_WRITE | SEQUENCERREGISTER_SHIFT:
			return getHandshakeRegister();
		case SEQUENCERREGISTER_WRITE | SEQUENCERREGISTER_LOAD:
			if (!isDriveEnabled)
				setModeRegister(value);
			else {
				if (isAsynchronousMode) {
					writeDataRegister = value;
					isWriteDataReady = false;
				} else
					shiftRegister = value;
			}
			break;
	}
	
	return 0xff;
}

void IWM::setModeRegister(UINT8 value) {
	printf("setModeRegister:%02x\n", value);
	modeRegister = value;
	
	isLatchMode = getBit(value, IWMMODE_LATCHMODE);
	isAsynchronousMode = getBit(value, IWMMODE_ASYNCHMODE);
	isDriveTimerEnabled = !getBit(value, IWMMODE_DRIVETIMERDISABLE);
	bitCellShift = getBit(value, IWMMODE_2MSBITCELLS) ? 2 : 3;
	
	if (motorOffFrameIndex && !isDriveTimerEnabled) {
		motorOffFrameIndex = 0;
		isDriveEnabled = false;
		selectedPort->setDriveEnabled(false);
	}
}

UINT8 IWM::getStatusRegister() {
	UINT8 statusRegister = modeRegister;
	setBit(statusRegister, IWMSTATUS_DRIVEENABLED, isDriveEnabled);
	setBit(statusRegister, IWMSTATUS_MZ, 0);
	setBit(statusRegister, IWMSTATUS_SENSEINPUT, selectedPort->senseInput());
	
	printf("getStatusRegister:%02x\n", statusRegister);
	
	return statusRegister;
}

UINT8 IWM::getHandshakeRegister() {
	UINT8 handshakeRegister = 0xff;
	setBit(handshakeRegister, IWMHANDSHAKE_WRITESTATE, !isWriteUnderrun);
	setBit(handshakeRegister, IWMHANDSHAKE_WRITEDATAREADY, isWriteDataReady);
	
	printf("getHandshakeRegister:%02x\n", handshakeRegister);
	
	return handshakeRegister;
}
